// pages/ control/control.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canSubmit: true, // 是否可以发起请求（防止过度请求）
    onOff: true, // 氛围灯开启
    leader: false, // 主从配对
    doorWarn: false, // 开门警告开启
    showArea: '统一',
    showAreaCode: 0,
    showMode: '单色常亮',
    showModeCode: 1,
    areas: [
      {name: '统一', code: 0},
      {name: '分区1', code: 1},
      {name: '分区2', code: 2},
      {name: '炫彩', code: 3},
    ],
    modesCopy: [
      { name: '关闭', code: 0},
      { name: '单色常亮', code: 1},
      { name: '单色呼吸', code: 2},
      { name: '渐变模式', code: 3},
      { name: '爆闪模式', code: 4},
      { name: '律动模式', code: 5},
      { name: '多色呼吸', code: 6}
    ], //   模式
    modes: [
      { name: '关闭', code: 0},
      { name: '单色常亮', code: 1},
      { name: '单色呼吸', code: 2},
      { name: '渐变模式', code: 3},
      { name: '爆闪模式', code: 4},
      { name: '律动模式', code: 5},
      { name: '多色呼吸', code: 6}
    ], //   模式
    showLight: 10,
    rgb: 'rgb(255,0,0)',
    R: 255,
    G: 0,
    B: 0,
    pick: false,
    current: 0, // 经典色彩当前色块 0红色 1橙色 2黄色 3绿色 4蓝色 5紫色

    colorData: {
      //基础色相，即左侧色盘右上顶点的颜色，由右侧的色相条控制
      hueData: {
          colorStopRed: 255,
          colorStopGreen: 0,
          colorStopBlue: 0,
      },
      //选择点的信息（左侧色盘上的小圆点，即你选择的颜色）
      pickerData: {
          x: 480, //选择点x轴偏移量
          y: 0, //选择点y轴偏移量
          red: 0, 
          green: 0,
          blue: 0, 
          hex: '#ff0000'
      },
      //色相控制条的位置
      barY: 124
    },
    rpxRatio: 1, //此值为你的屏幕CSS像素宽度/750，单位rpx实际像素
    wind: 0, // 通风 0关闭 1低 2中 3高
    fragrance: 0, // 香氛 0关闭 1低 2中 3高
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const _this = this
    //设置rpxRatio
    wx.getSystemInfo({
      success(res) {
          _this.setData({
              rpxRatio: res.screenWidth / 750
          })
      }
    })

    if(wx.getStorageSync('control')){
      console.log(wx.getStorageSync('control'),123132)
      this.setData({
        ...wx.getStorageSync('control'),
      })
      this.onChangeColor(wx.getStorageSync('colorItem'))
    }
  },

  //选择改色时触发（在左侧色盘触摸或者切换右侧色相条）
  onChangeColor(e) {
    //返回的信息在e.detail.colorData中
    console.log(e)
    let colorData = {
      hueData: e.detail.colorData.hueData,
      pickerData: e?.detail?.colorData?.pickerData,
      barY: e?.detail?.colorData?.barY
    }
    let rgb = e.detail.colorData.pickerData;
    let R = rgb.red;
    let G = rgb.green;
    let B = rgb.blue;
    this.setData({
      R: Number(R),
      G: Number(G),
      B: Number(B),
      colorData,
      showMode: '单色常亮',
      showModeCode: 1,
    })
    wx.setStorageSync('colorItem', e)
    let arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
    let code = [46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, Number(R), Number(G), Number(B)]
    let lastCode = app.sum(code);
    code.push(lastCode);
    console.log(code)
    this.writeBLE(code)
  },

  // 自定义取色
  pickColor(e) {
    let rgb = e.detail.color;
    let R = rgb.split(',')[0].split('(')[1];
    let G = rgb.split(',')[1];
    let B = rgb.split(',')[2].split(')')[0];
    this.setData({
      R: Number(R),
      G: Number(G),
      B: Number(B),
      showMode: '单色常亮',
      showModeCode: 1,
      rgb: rgb
    })
    console.log("当前色值", R, G, B, rgb)
    let arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
    let code = [46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, Number(R), Number(G), Number(B)]
    let lastCode = app.sum(code);
    code.push(lastCode);
    this.writeBLE(code)
  },

  // 按钮变化
  onChange(e){
    const code = e.target.dataset.code;
    let cod = []
    const { R, G, B } = this.data;
    switch(code){
      case 'on':
        this.setData({
          onOff: !this.data.onOff
        })
        let arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
        cod = [46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, Number(R), Number(G), Number(B)]
        cod.push(app.sum(cod));
        this.writeBLE(cod)
        break
      case 'leader':
        this.setData({
          leader: !this.data.leader
        })
        arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
        cod = [46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, Number(R), Number(G), Number(B)]
        cod.push(app.sum(cod));
        this.writeBLE(cod)
        break
      case 'door':
        this.setData({
          doorWarn: !this.data.doorWarn
        })
        arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
        cod = [46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, Number(R), Number(G), Number(B)]
        cod.push(app.sum(cod));
        this.writeBLE(cod)
        break
      case 'auto':
        if(e.detail.value == true){
          arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
          let code = [46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, Number(R), Number(G), Number(B)]
          code.push(app.sum(code));
          this.writeBLE(code)
          this.setData({
            pick: true
          })
        }else{
          switch(this.data.current){
            case 0:
              this.setData({
                R: 255,
                G: 0,
                B: 0,
              })
              break
            case 1:
              this.setData({
                R: 255,
                G: 165,
                B: 0,
              })
              break
            case 2:
              this.setData({
                R: 255,
                G: 255,
                B: 0,
              })
              break
            case 3:
              this.setData({
                R: 0,
                G: 128,
                B: 0,
              })
              break
            case 4:
              this.setData({
                R: 0,
                G: 0,
                B: 255,
              })
              break
            case 5:
              this.setData({
                R: 128,
                G: 0,
                B: 128,
              })
              break
          }
          console.log("当前色值", R, G, B)
          arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
          let code = [46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, Number(R), Number(G), Number(B)]
          code.push(app.sum(code));
          this.writeBLE(code)
          this.setData({
            pick: false
          })
        }
        break
    }
  },

  // 选择分区
  changeArea(e) {
    console.log(e.detail.value)
    if(e.detail.value == 3){
      let arr = [
        { name: '单色流水A', code:10},
        { name: '单色流水B', code:11},
        { name: '单色流水C', code:12},
        { name: '单色流水D', code:13},
        { name: '7色流水A', code:14},
        { name: '7色流水B', code:15},
        { name: '酷炫模式A', code:16},
        { name: '酷炫模式B', code:17},
        { name: '酷炫模式C', code:18},
        { name: '酷炫模式D', code:19},
        { name: '酷炫模式E', code:20},
        { name: '酷炫模式F', code:21},
        { name: '酷炫律动A', code:22},
        { name: '酷炫律动B', code:23},
        { name: '酷炫律动C', code:24},
        { name: '酷炫律动D', code:25},
        { name: '酷炫律动E', code:26},
        { name: '酷炫律动F', code:27},
        { name: '扩展1', code:28},
        { name: '扩展2', code:28},
        { name: '扩展3', code:30},
      ]
      this.setData({
        modes: [...this.data.modes, ...arr]
      })
    }else {
      this.setData({
        modes: this.data.modesCopy,
        showModeCode: this.data.showModeCode > 6 ? 1 : this.data.showModeCode,
        showMode: this.data.showModeCode > 6 ? '单色常亮' : this.data.showMode,
      })
    }
    this.setData({
      showArea: this.data.areas[e.detail.value].name,
      showAreaCode: this.data.areas[e.detail.value].code,
    })
    let arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
    let code =[46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, this.data.R, this.data.G, this.data.B];
    let lastCode = app.sum(code);
    code.push(lastCode);
    this.writeBLE(code)
  },

  // 选择模式
  changeMode(e) {
    this.setData({
      showMode: this.data.modes[e.detail.value].name,
      showModeCode: this.data.modes[e.detail.value].code
    })
    let arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
    let code =[46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, this.data.R, this.data.G, this.data.B];
    let lastCode = app.sum(code);
    code.push(lastCode);
    this.writeBLE(code)
    console.log(e)
  },

  // 调节亮度
  changeLight(e){
    this.setData({
      showLight: e.detail.value
    })
    let arr3 = (this.data.onOff ? '1' : '0') + (this.data.leader ? '1' : '0') + (this.data.doorWarn ? '1' : '0') + '00000';
    let code = [46, 10, parseInt(arr3, 2), this.data.showAreaCode, this.data.showModeCode, this.data.showLight, this.data.R, this.data.G, this.data.B,];
    let lastCode = app.sum(code);
    code.push(lastCode);
    this.writeBLE(code)
  },

  // 确定亮度
  sliderChange(e){
  },

  // 座椅通风
  sliderWind(e){
    this.setData({
      wind: e.detail.value
    })
    let code = [46, 12, e.detail.value, 0, 0, 0, 0];
    let lastCode = app.sum(code);
    code.push(lastCode);
    this.writeBLE(code)
  },
  // 香氛
  sliderFragrance(e){
    this.setData({
      fragrance: e.detail.value
    })
    let code = [46, 13, e.detail.value, 0, 0, 0, 0];
    let lastCode = app.sum(code);
    code.push(lastCode);
    this.writeBLE(code)
  },

  // 全局调用写入蓝牙
  writeBLE(code) { //分区参数
    if(!this.data.canSubmit){
      return
    }
    let d = app.globalData;
    let buffer = new ArrayBuffer(10);
    let dataView = new DataView(buffer);
    code.forEach((v, i) => dataView.setUint8(i, v))
    console.log(dataView, code);
    const that = this;
    this.setData({
      canSubmit: false
    })
    wx.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: d.deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId: d.serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId: d.characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      success: (res) => {
        console.log('写入蓝牙成功', res.errMsg);
        let controlData = {
          onOff: that.data.onOff, // 氛围灯开启
          leader: that.data.leader, // 主从配对
          doorWarn: that.data.doorWarn, // 开门警告开启
          showArea: that.data.showArea,
          showAreaCode: that.data.showAreaCode,
          showMode: that.data.showMode,
          showModeCode: that.data.showModeCode,
          showLight: that.data.showLight,
          rgb: that.data.rgb,
          R: that.data.R,
          G: that.data.G,
          B: that.data.B,
          current: that.data.current,
          colorData: that.data.colorData,
          wind: that.data.wind,
          fragrance: that.data.fragrance,
        }
        wx.setStorageSync('control', controlData)
      },
      fali: (err) => {
        console.log('写入蓝牙失败', err);
        app.Toast('修改失败,请检查蓝牙是否打开！')
      },
      complete: (data) => {
        that.setData({
          canSubmit: true
        })
      }
    })
  },

})